package com.wx.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import com.eova.common.Easy;
import com.eova.common.utils.xx;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.wx.model.PartyGetBonusRecord;
import com.wx.model.PartyInfo;
import com.wx.model.PartyLotteryNum;
import com.wx.model.PartyPrizeDetail;
import com.wx.model.PartyPrizeGroup;
import com.wx.model.PartyPrizeRecord;
import com.wx.model.PartyPrizeSummary;
import com.wx.model.PartyRule;
import com.wx.model.PartyTicket;
import com.wx.model.PartyTicketDetail;
import com.wx.model.PartyUser;
import com.wx.model.PartyUserSerinfo;
import com.wx.sql.MarketingSql;
import com.xiaoleilu.hutool.date.DateUtil;
import com.xiaoleilu.hutool.http.HttpUtil;
import com.xiaoleilu.hutool.json.JSONUtil;

/**
 * ClassName: MarketingService 
 * @Description:营销类接口实现类
 * @author liuxin
 * @date 2018年5月17日
 */
public class UserIndexService { 
	public static final UserIndexService me = new UserIndexService();
	private final PartyUser userDao = new PartyUser().dao();
	private final PartyRule ruleDao = new PartyRule().dao();
	private final PartyLotteryNum lotteryNumDao = new PartyLotteryNum().dao();
	private final PartyUserSerinfo userSerinfoDao = new PartyUserSerinfo().dao();
	private final PartyInfo partyInfoDao = new PartyInfo().dao();
	private final PartyPrizeGroup partyPrizeGroupDao = new PartyPrizeGroup().dao();
	private final PartyPrizeDetail partyPrizeDetailDao = new PartyPrizeDetail();
	private final PartyTicket ticketDao = new PartyTicket();
	private final PartyPrizeSummary prizeSummaryDao = new PartyPrizeSummary();
	/**
	 * @Description: 获得奖励次数
	 * @param @param map:
	 * {
	 * 	USER_CODE:"1001",用户编码
	 *  USER_SOURCE:"0",(0:江津，1:常州),
	 *  USER_TYPE:"1001",用户类型
	 *  LOGIN_NUM："2",签到次数
	 *  ORDER_NUM："2",下单次数
	 *  REPEAT_NUM："2",转发次数
	 *  PARTY_ID:"1001"活动ID
	 * }
	 * @param @return   
	 * @return Map<String,Object>  
	 * @throws
	 * @author liuxin
	 * @date 2018年5月17日
	 */
	public Ret getNumberOfAwards(PartyUser user,int party_id) {
		Ret ret = new Ret();
		//获取活动信息
		PartyInfo party = partyInfoDao.findById(party_id);
		//获取请求URL
		String actionUrl = xx.getConfig(user.getUserSource()+"URL")+"api.php?controller=jackpot&action=getUserInfo";
		//获取用户在此活动已抽奖次数
		Record r = Db.findFirst("select ifnull(sum(prize_num),1) maxcs from party_get_bonus_record d where d.user_id = ? and d.party_id =?",user.getId(),party_id);
		int maxcs = 0;
		int dtcs = 0;
		if(r !=null){
			if(r.getInt("maxcs")==0){
				maxcs = 1;
			}else{
				maxcs = r.getInt("maxcs");
			} 
		}
		//获取奖励规则
		List<PartyRule> partyRuleList = PartyRule.dao.find("select * from party_rule d where d.party_id = ?",party_id);
		PartyRule pr = partyRuleList.get(0);
		//获取用户当天在此活动已抽奖次数
		r = Db.findFirst("select  ifnull(sum(prize_num),0) num from party_get_bonus_record d where d.user_id=? and to_days(d.create_time) = to_days(now()) ",user.getId());
		if(r !=null){
			dtcs = r.getInt("num");
		}
		
		
		if(pr.getLimitOrderNum()<=dtcs||maxcs>=party.getMaxnum()){
			//已获得最大抽奖次数，无法在进行抽奖
			List<PartyLotteryNum> partyLotteryNumList = PartyLotteryNum.dao.find("select * from party_user_lottery_num d where d.user_id =? and d.party_id = ?",user.getId(),party_id);
			PartyLotteryNum p = null;
			if(partyLotteryNumList.size()>0){
				p = partyLotteryNumList.get(0);
				ret.set("CJCS", p.getLotteryNum());
				ret.ok();
			}else{
				ret.set("CJCS", 0);
				ret.ok();
			}
		}else{
			//获取用户拉取时间信息
			List<PartyUserSerinfo> userSerinfoList = userSerinfoDao.find("select * from party_user_serinfo d where d.user_id=? and d.party_id =?",user.getId(),party_id);
			Date lastTime = new Date();
			Date now = new Date();
			PartyUserSerinfo pus = null;
			if(userSerinfoList.size()>0){
				//已加入过此活动,获取最晚一次抽奖时间
				pus=userSerinfoList.get(0);
				lastTime = userSerinfoList.get(0).getLastSerTime();
			}else{
				pus = new PartyUserSerinfo();
				//小于0时表示第一次加入此活动以活动开始时间为主
				lastTime = party.getStartTime();
			}
			
			//请求tmm
			Map paramMap=new HashMap<>();
			paramMap.put("key", user.getRequestKey());
			paramMap.put("start_time", DateUtil.format(lastTime, "yyyy-MM-dd HH:mm:ss"));
			paramMap.put("end_time", DateUtil.format(now, "yyyy-MM-dd HH:mm:ss"));
			String response = HttpUtil.post(actionUrl, paramMap);
			System.out.println("======="+response);
			Map map = JSONUtil.parseObj(response);
			if(map.get("errcode")!=null&&(int)map.get("errcode")==0){
				
				if(partyRuleList.size()>0){
					
					//签到次数
					int qdcs = (int) ((Map)map.get("info")).get("sign_nums");
					//下单次数
//					int xdcs =  (int) ((Map)map.get("info")).get("order_nums");
					int xdcs =  0;
					//计算抽奖次数
					int cs = pr.getLoginNum()*qdcs+pr.getOrderNum()*xdcs;
					if(cs>0){
//						if(cs>maxcs){
//							//大于最大抽奖次数时
//							cs = maxcs;
//						}
						if(cs+dtcs>=pr.getLimitOrderNum()){
							cs = pr.getLimitOrderNum() - dtcs;
						}
						//更新用户剩余次数表
						List<PartyLotteryNum> partyLotteryNumList = PartyLotteryNum.dao.find("select * from party_user_lottery_num d where d.user_id =? and d.party_id = ?",user.getId(),party_id);
						PartyLotteryNum p = null;
						if(partyLotteryNumList.size()>0){
							p = partyLotteryNumList.get(0);
							p.setLotteryNum(p.getLotteryNum()+cs);
							p.setUpdateDate(now);
							p.update();
						}else{
							p = new PartyLotteryNum();
							p.setLotteryNum(cs);
							p.setCreateDate(now);
							p.setPartyId(party_id);
							p.setUserId(user.getId());
							p.save();
						}
						//新增用户抽奖记录表
						PartyGetBonusRecord pubs  = new PartyGetBonusRecord();
						pubs.setCreateTime(new Date());
						pubs.setPartyId(party_id);
						pubs.setPrizeNum(cs);
						pubs.setUserId(user.getId());
						pubs.save();
						ret.set("CJCS", p.getLotteryNum());
						ret.ok();
					}
				}else{
					
				}
			}else{
				List<PartyLotteryNum> partyLotteryNumList = PartyLotteryNum.dao.find("select * from party_user_lottery_num d where d.user_id =? and d.party_id = ?",user.getId(),party_id);
				PartyLotteryNum p = null;
				if(partyLotteryNumList.size()>0){
					p = partyLotteryNumList.get(0);
					ret.set("CJCS", p.getLotteryNum());
					ret.ok();
				}else{
					ret.set("CJCS", 0);
					ret.ok();
				}
			}
			if(pus.getId()!=null){
				pus.setLastSerTime(now);
				pus.setUpdateDate(now);
				pus.update();
			}else{
				pus.setCreateDate(now);
				pus.setLastSerTime(now);
				pus.setPartyId(party_id);
				pus.setUserId(user.getId());
				pus.save();
				
			}
		}
		if(ret.get("CJCS")==null){
			//已获得最大抽奖次数，无法在进行抽奖
			List<PartyLotteryNum> partyLotteryNumList = PartyLotteryNum.dao.find("select * from party_user_lottery_num d where d.user_id =? and d.party_id = ?",user.getId(),party_id);
			PartyLotteryNum p = null;
			if(partyLotteryNumList.size()>0){
				p = partyLotteryNumList.get(0);
				ret.set("CJCS", p.getLotteryNum());
				ret.ok();
			}else{
				ret.set("CJCS", 0);
				ret.ok();
			}
		}
		
		return ret;
		
	}
	
	/**
	 * @Description: 获取用户所得奖励
	 * @param @param map
	 * {
	 * USER_CODE:"1001",用户编码，
	 * PARTY_ID:"1001"活动ID
	 * }
	 * @param @return   
	 * @return Easy  
	 * @throws
	 * @author liuxin
	 * @date 2018年5月18日
	 */
	public Easy getAReward(Map<String, Object> map){
		Easy easy = new Easy();
		//
		List<PartyLotteryNum> lotteryNumList = lotteryNumDao.find(MarketingSql.getLotteryNum(map));
		if(lotteryNumList.size() > 0){
			PartyLotteryNum	partyLotteryNum = lotteryNumList.get(0);
			if(partyLotteryNum.getLotteryNum() > 0){
				PartyInfo partyInfo = partyInfoDao.findById(map.get("PARTY_ID"));
				Date now = new Date();
				if(now.after(partyInfo.getEndTime())){
					easy.setMsg("活动已经结束了哦！");
					easy.setSuccess(true);
				}else if(now.before(partyInfo.getStartTime())){
					easy.setMsg("活动还没开始哦！");
					easy.setSuccess(true);
				}else{
					PartyUser user = userDao.findFirst("select * from party_user where user_code = '"+map.get("USER_CODE")+"'");
					PartyPrizeGroup prizeGroup = partyPrizeGroupDao.findFirst(MarketingSql.getPrizeGroup(map));
					//获取奖励明细()
					List<PartyPrizeDetail>  prizeDetailList = partyPrizeDetailDao.find(MarketingSql.getPrizeDetail(prizeGroup.getId()));
					//最终参与抽奖的奖励明细（排除没有达到阀值的和奖励商品券剩余数量为0 的）
					List<PartyPrizeDetail> partyPrizeDetailList = new ArrayList<PartyPrizeDetail>() ;
					//总概率
					int sum = 0;
					for(PartyPrizeDetail prizeDetail :prizeDetailList ){
						//获取奖励券（判断奖励券是否有剩余）
						PartyTicket ticket = ticketDao.findFirst(MarketingSql.getTicket(prizeDetail.getTicketId()));
						//=========================================================//
						//总的参与人数
						int party_num = 0;
						//该奖项已发个数 
						int prize_num = 0;
						List<PartyPrizeSummary> prizeSummarieList = prizeSummaryDao.find(MarketingSql.getPrizeSummary(prizeDetail.getId()));
						if(prizeSummarieList.size() > 0){
							prize_num = prizeSummarieList.get(0).getPrizeNum();
						}
						//个人 、总体 （判断阀值）
						if(prizeDetail.getThresholdType() == 0){
							party_num = Db.queryInt("SELECT COUNT(ID) FROM party_prize_record WHERE party_id = "+map.get("PARTY_ID")+" AND user_id = "+user.getId()+"" );
						}else{
							party_num = Db.queryInt("SELECT SUM(IFNULL(prize_num,0)) FROM party_prize_summary WHERE party_id = "+map.get("PARTY_ID")+"");
						}
						System.out.println("=================" + party_num + "     " + prize_num);
						//阀值计算方式：（奖励已发次数+1） * 下线阀值系数
						if(party_num >= (prize_num+1) * prizeDetail.getThreshold()){
							if(ticket != null && ticket.getResidualQuantity() > 0){
								partyPrizeDetailList.add(prizeDetail);
								sum += prizeDetail.getPrizeProbability();
							}
						}
						//=======================================================//
						
					}
					//kai shi chou jiang
					Random random = new Random();  
					//sui ji chan sheng zhong jiang hao ma ,pan duan gai hao hao ma chu yu na ge duan 
					int num = random.nextInt(sum); 
					int total = 0;
					int preNum = 0;
					PartyPrizeDetail reward = null ;
					for(PartyPrizeDetail prizeDetail :partyPrizeDetailList){
						total += prizeDetail.getPrizeProbability();
						if(num >= preNum && num <total){
							reward = prizeDetail;
							break;
						}
						preNum += prizeDetail.getPrizeProbability();
					}
					//==========================geng xin biao xin xi================================//
					//奖励商品券
					PartyTicket ticket = ticketDao.findFirst(MarketingSql.getTicket(reward.getTicketId()));
					ticket.setResidualQuantity(ticket.getResidualQuantity() - 1);
					ticket.update();
					// 商品券明细表
					PartyTicketDetail ticketDetail = new PartyTicketDetail();
					ticketDetail.setLotteryTime(new Date());
					ticketDetail.setTicketId(ticket.getId());
					ticketDetail.setTicketStatus(1);
					ticketDetail.setUserId(user.getId());
					ticketDetail.save();
					//商品奖励信息汇总表
					PartyPrizeSummary prizeSummary  ;
					List<PartyPrizeSummary> prizeSummarieList = prizeSummaryDao.find(MarketingSql.getPrizeSummary(reward.getId()));
					if(prizeSummarieList.size() > 0){
						prizeSummary  = prizeSummarieList.get(0);
						prizeSummary.setPrizeNum(prizeSummary.getPrizeNum() + 1 );
						prizeSummary.setUpdateDate(new Date());
						prizeSummary.update();
					}else{
						prizeSummary = new PartyPrizeSummary();
						prizeSummary.setPrizeNum(1);
						prizeSummary.setPrizeId(reward.getId());
						prizeSummary.setPartyId(Integer.parseInt(map.get("PARTY_ID").toString()));
						prizeSummary.save();
					}
					//参与活动明细表
					PartyPrizeRecord prizeRecord = new PartyPrizeRecord();
					prizeRecord.setPartyId(Integer.parseInt(map.get("PARTY_ID").toString()));
					prizeRecord.setPrizeId(reward.getId());
					prizeRecord.setPrizeName(reward.getPrizeName());
					prizeRecord.setUserId(user.getId());
					prizeRecord.setParticipationTime(new Date());
					prizeRecord.save();
					//用户资源表
					partyLotteryNum.setLotteryNum(partyLotteryNum.getLotteryNum() - 1);
					partyLotteryNum.setUpdateDate(new Date());
					partyLotteryNum.update();
					//确定抽奖
					easy.setData(reward);
					easy.setMsg("SUCCESS");
					easy.setSuccess(true);
				}
			}else{
				easy.setMsg("您的抽奖次数已经用完了哦！");
				easy.setSuccess(true);
			}
		}
		return easy;
	}
	
	/**
	 * @Description: 更新用户资源
	 * @param @param map
	 * @param @param rule   
	 * @return void  
	 * @throws
	 * @author liuxin
	 * @date 2018年5月17日
	 */
	public Map<String, Object> updateLotteryNum(Map<String, Object> map,PartyRule rule){
		Map<String, Object> resultMap = new HashMap<String, Object>(2);
		//这段时间内该用户获取的总的奖励次数
		PartyLotteryNum partyLotteryNum = null;
		int lotteryNum = 0;
		if(null!=map.get("LOGIN_NUM")&&""!=map.get("LOGIN_NUM")){
			//增加签到获取次数
			lotteryNum +=Integer.parseInt(map.get("LOGIN_NUM").toString()) * rule.getLoginNum();
		}
		if(null!=map.get("ORDER_NUM")&&""!=map.get("ORDER_NUM")){
			//增加下单获得次数
			lotteryNum +=Integer.parseInt(map.get("ORDER_NUM").toString())  * rule.getOrderNum();
		}
		if(null!=map.get("REPEAT_NUM")&&""!=map.get("REPEAT_NUM")){
			//增加转发获得次数
			lotteryNum +=Integer.parseInt(map.get("REPEAT_NUM").toString())  * rule.getRepeatNum();
		}
		
		List<PartyLotteryNum> lotteryNumList = lotteryNumDao.find(MarketingSql.getLotteryNum(map));
		//用户资源已经存在，则更新用户资源,否则新增一条用户资源
		if(lotteryNumList.size() > 0){
			partyLotteryNum = lotteryNumList.get(0);
			partyLotteryNum.setLotteryNum(lotteryNum + partyLotteryNum.getLotteryNum());
			partyLotteryNum.setUpdateDate(new Date());
			partyLotteryNum.update();
		}else{
			partyLotteryNum = new PartyLotteryNum();
			partyLotteryNum.setLotteryNum(lotteryNum);
			partyLotteryNum.setUserId((Integer)map.get("USER_ID"));
			partyLotteryNum.setPartyId((Integer)map.get("PARTY_ID"));
			partyLotteryNum.save();
		}
		resultMap.put("lotteryNum",lotteryNum );
		resultMap.put("partyLotteryNum",partyLotteryNum );
		return resultMap;
	}
	
	/**
	 * @Description:更新用户信息拉取表
	 * @param @param map   
	 * @return void  
	 * @throws
	 * @author liuxin
	 * @date 2018年5月17日
	 */
	public void updateUserSerInfo(Map<String,Object> map) {
		List<PartyUserSerinfo> userSerinfoList = userSerinfoDao.find(MarketingSql.getUserSerInfo(map));
		PartyUserSerinfo userSerinfo = null;
		if(userSerinfoList.size() > 0){
			userSerinfo = userSerinfoList.get(0);
			userSerinfo.setUpdateDate(new Date());
			userSerinfo.setLastSerTime(new Date());
			userSerinfo.update();
		}else{
			userSerinfo = new PartyUserSerinfo();
			userSerinfo.setLastSerTime(new Date());
			userSerinfo.setUserId((Integer)map.get("USER_ID"));
			userSerinfo.setPartyId((Integer)map.get("PARTY_ID"));
			userSerinfo.save();
		}
	}
	
	
	
}
